<!-- 设备维修-维修申报页面 -->
<template>
  <div>
    <div v-show="isMain" class="equip-wrap-common">
      <px-form ref="searchFormRef" class="custom-form-ui equip-form" :model="queryParams" label-position="right" label-width="120px">
        <px-row :gutter="16">
          <px-col :span="5">
            <px-form-item label="盘点计划名称/编号" prop="planNameOrCode">
              <px-input
                v-model="queryParams.planNameOrCode"
                placeholder="请输入盘点计划名称/编号"
                maxlength="50"
                clearable
                @blur="queryParams.planNameOrCode = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="5">
            <EquipClassSelect :className="queryParams.className" @changeClassName="changeClassName" />
          </px-col>
          <px-col :span="5">
            <px-form-item label="执行状态" prop="planStatus">
              <px-select v-model="queryParams.planStatus" placeholder="请选择执行状态" clearable filterable>
                <px-option v-for="item in statusList" :key="item.value" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="5">
            <px-form-item label="创建人" prop="createBy">
              <px-select-v2
                v-model="queryParams.createBy"
                style="width: 100%"
                filterable
                clearable
                :options="approvalList"
                placeholder="请选择创建人"
              />
            </px-form-item>
          </px-col>
          <px-col :span="4">
            <px-button type="primary" @click="queryTable">查询</px-button>
            <px-button @click="resetTable">重置</px-button>
          </px-col>
        </px-row>
      </px-form>
      <div class="equip-table-btn">
        <px-button v-has="'ALL_EQUIP_TOOL_PLAN_ADD'" style="margin-right: 10px" icon="Plus" type="primary" @click="handleAdd">
          新建盘点计划
        </px-button>
      </div>
      <px-table :data="tableData" class="equip-table" size="small" height="calc(100vh - 313px)" border>
        <px-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :label="item.label"
          :min-width="item.minWidth"
          :align="item.align"
          :show-overflow-tooltip="item.showOverflowTooltip"
          :fixed="item.fixed"
        >
          <template v-if="item.type === 'status'" #default="scope">
            <div class="status">
              <div class="circle" :style="{ backgroundColor: `${tagBgColorList[scope.row.planStatus]}` }" />
              <p :style="{ color: `${tagBgColorList[scope.row.planStatus]}` }">{{ scope.row.planStatusDesc }}</p>
            </div>
          </template>
          <template v-else-if="item.type === 'link'" #default="scope">
            <span v-if="isHasPermission('ALL_EQUIP_TOOL_PLAN_DETAIL')" style="color: #3b82f6; cursor: pointer" @click="handleView(scope.row)">
              {{ scope.row.takePlanCode }}
            </span>
            <span v-else>{{ scope.row.takePlanCode }}</span>
          </template>
          <template v-else-if="item.type === 'date'" #default="scope">
            <px-tooltip :content="`${scope.row.execStartDate}~${scope.row.execEndDate}`" placement="top">
              <span>{{ scope.row.execStartDate }}~{{ scope.row.execEndDate }}</span>
            </px-tooltip>
          </template>
          <template v-else #default="scope">{{
            scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-"
          }}</template>
        </px-table-column>
        <px-table-column fixed="right" label="操作" min-width="160" align="center">
          <template #default="scope">
            <px-tooltip content="详情" placement="top">
              <px-button v-has="'ALL_EQUIP_TOOL_PLAN_DETAIL'" link type="primary" icon="Tickets" @click="handleView(scope.row)" />
            </px-tooltip>
            <px-tooltip content="复制" placement="top">
              <px-button v-has="'ALL_EQUIP_TOOL_PLAN_COPY'" link type="primary" icon="DocumentCopy" @click="handleCopy(scope.row)" />
            </px-tooltip>
            <px-tooltip v-if="[1, 2].includes(scope.row.planStatus)" content="编辑" placement="top">
              <px-button v-has="'ALL_EQUIP_TOOL_PLAN_EDIT'" link type="primary" icon="EditPen" @click="handleEdit(scope.row)" />
            </px-tooltip>
            <px-tooltip v-if="[2].includes(scope.row.planStatus)" content="取消" placement="top">
              <px-button v-has="'ALL_EQUIP_TOOL_PLAN_CANCEL'" link type="primary" icon="CircleClose" @click="handleCancel(scope.row)" />
            </px-tooltip>
            <px-tooltip v-if="scope.row.planStatus === 3" content="修改计划" placement="top">
              <px-button v-has="'ALL_EQUIP_TOOL_PLAN_EDIT'" link type="primary" icon="EditPen" @click="handleEditPlan(scope.row)" />
            </px-tooltip>
            <px-tooltip v-if="[1, 5].includes(scope.row.planStatus)" content="删除" placement="top">
              <px-button v-has="'ALL_EQUIP_TOOL_PLAN_DELETE'" link type="danger" icon="Delete" @click="handleDelete(scope.row)" />
            </px-tooltip>
            <px-tooltip v-if="[3, 4].includes(scope.row.planStatus)" content="查看任务" placement="top">
              <px-button
                v-have="['ALL_EQUIP_TOOL_PLAN_VIEW_TASK', 'ALL_EQUIP_TOOLMANAGE_INVENTORY_VIEWPAGE']"
                link
                type="primary"
                icon="Browse"
                @click="handleViewTask(scope.row)"
              />
            </px-tooltip>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="equip-table-pagination"
        :total="total"
        @pagination="queryTable"
      />
    </div>
    <!-- 新增页面 -->
    <AddPlan
      :isMain="isMain"
      :isView="isView"
      :planId="planId"
      :drawerType="drawerType"
      :shareData="{ faultSourceList }"
      @queryTable="queryTable"
      @backMainPage="backMainPage"
    />
    <ViewPlanDetail
      :isMain="isMain"
      :isView="isView"
      :planId="planId"
      @handleCopy="handleCopy"
      @handleEdit="handleEdit"
      @backMainPage="backMainPage"
      @queryTable="queryTable"
    />
    <EditPlanDialog
      :visible="isEditPlanShow"
      :planId="planId"
      @closeDialog="
        isEditPlanShow = false;
        planId = '';
      "
      @queryTable="queryTable"
    />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ALL_EQUIP_TOOL_PLAN"
});
import { queryDictData } from "@/api/common";
import { cancelToolInventoryList, delToolInventoryList, getToolInventoryList, getToolInventoryStatusList } from "@/api/equip/toolManage";
import { isHasPermission } from "@/utils/auth";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { onMounted, reactive, ref, toRefs } from "vue";
import { useRouter } from "vue-router";
import AddPlan from "./components/AddPlan.vue";
import EditPlanDialog from "./components/EditPlanDialog.vue";
import ViewPlanDetail from "./components/ViewPlanDetail.vue";

const router = useRouter();

const searchFormRef = ref();

const state = reactive<any>({
  userId: "",
  isMain: true, // 主页面true 详情页面false
  isView: false, // 查看true 新增/编辑false
  queryParams: {
    pageNum: 1,
    pageSize: 20
  },
  tableColumns: [
    { prop: "takePlanCode", label: "盘点计划编码", type: "link", minWidth: "130", showOverflowTooltip: true, fixed: "left" },
    { prop: "takePlanName", label: "盘点计划名称", minWidth: "120", showOverflowTooltip: true },
    { prop: "classNameDesc", label: "科室", minWidth: "80", showOverflowTooltip: true },
    { prop: "takeStockScopeDesc", label: "盘点范围", minWidth: "130", showOverflowTooltip: true },
    { prop: "execStartDate", label: "计划日期", type: "date", minWidth: "170", showOverflowTooltip: true },
    { prop: "planStatusDesc", label: "执行状态", minWidth: "100", type: "status", showOverflowTooltip: true },
    { prop: "createName", label: "创建人", minWidth: "120", showOverflowTooltip: true },
    { prop: "createTime", label: "创建时间", minWidth: "150", showOverflowTooltip: true }
  ],
  tableData: [],
  total: 0,
  drawerType: "add",
  planId: "",
  faultSourceList: [],
  approvalList: [],
  statusList: [], // 工单状态
  isEditPlanShow: false,
  rowData: {}
});
const {
  userId,
  isMain,
  isView,
  queryParams,
  tableColumns,
  tableData,
  total,
  drawerType,
  planId,
  faultSourceList,
  statusList,
  approvalList,
  isEditPlanShow,
  rowData
} = toRefs(state);

const tagBgColorList = {
  1: "#909399", // 草稿
  2: "#F59E0B", // 未开始
  3: "#3B82F6", // 进行中
  4: "#10B981", // 已结束
  5: "#909399" // 已取消
};

// 获取课室下拉列表
const queryClassNameSelect = async () => {
  faultSourceList.value = await queryDictData({ typeCode: "POINT_CHECK_SOURCE" });
  statusList.value = await getToolInventoryStatusList();
};

// 查询列表
const queryTable = async () => {
  const data = await getToolInventoryList({ ...queryParams.value });
  tableData.value = data?.data || [];
  total.value = data?.total || 0;
};
// 重置筛选条件列表
const resetTable = async () => {
  searchFormRef.value.resetFields();
  queryParams.value = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize
  };
  queryTable();
};

// 进入页面时触发
onMounted(async () => {
  const userInfo = JSON.parse(localStorage.getItem("userInfo"));
  userId.value = userInfo.userId;
  approvalList.value = await getEmployeeIdAndName();
  queryTable();
  queryClassNameSelect();
});

// 详情
const handleView = (row: any) => {
  isMain.value = false;
  isView.value = true;
  planId.value = row.id;
};
// 添加
const handleAdd = () => {
  drawerType.value = "add";
  isMain.value = false;
  isView.value = false;
};
// 编辑
const handleEdit = (row: any) => {
  drawerType.value = "edit";
  planId.value = row.id;
  isMain.value = false;
  isView.value = false;
};
// 复制
const handleCopy = (row: any) => {
  drawerType.value = "copy";
  planId.value = row.id;
  isMain.value = false;
  isView.value = false;
};
const handleEditPlan = (row: any) => {
  planId.value = row.id;
  isEditPlanShow.value = true;
};

// 查看任务
const handleViewTask = (row: any) => {
  router.push(`/all/equip/toolManage/inventory/index?code=${row.takePlanCode}&type=list`);
};
// 取消
const handleCancel = (row: any) => {
  PxMessageBox.confirm(`确认取消该计划吗？`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    draggable: true,
    type: "warning"
  })
    .then(async () => {
      await cancelToolInventoryList(row.id);
      PxMessage.success("取消成功");
      queryTable();
    })
    .catch(() => {});
};
// 删除
const handleDelete = async (row: any) => {
  PxMessageBox.confirm(`请确认是否删除该条内容，删除后不可恢复`, "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await delToolInventoryList(row.id);
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};
// 从新增/编辑、详情返回主页面
const backMainPage = () => {
  planId.value = "";
  isMain.value = true;
  drawerType.value = "";
};

// 科室组件调用父组件
const changeClassName = val => {
  queryParams.value.className = val;
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/table-list.scss");

.status {
  display: flex;
  flex-direction: row;
  align-items: center;

  .circle {
    width: 8px;
    height: 8px;
    margin-right: 5px;
    border-radius: 50%;
  }
}
</style>
